﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TjZheng.Base;
using TjZheng.Power.DataEntity;
using TjZheng.Framework;
using TjZheng.Power.Business;
using TjZheng.Redis;
using TjZheng.Power.RedisEntity;
using TjZheng.Cache;

namespace TjZheng.CMS.Process.Business
{
    public partial class UserProcess
    {
        /// <summary>
        /// 是否从Redis检查用户权限
        /// </summary>
        protected bool IsCheckUserPowerRedis
        {
            get
            {
                return ConfigHelper.GetBoolValue("IsCheckUserPowerRedis", true);
            }
        }
        /// <summary>
        /// 用户组权限-保存
        /// </summary>
        /// <param name="objGroupPowerInfoList"></param>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public InvokeResult SaveGroupPower(List<GroupPowerInfo> objGroupPowerInfoList, long groupId)
        {
            if (objGroupPowerInfoList.IsNull())
            {
                objGroupPowerInfoList = new List<GroupPowerInfo>();
            }
            BizGroupPowerInfo objBizGroupPowerInfo = new BizGroupPowerInfo();
            var objGroupPowerInfoListOld = objBizGroupPowerInfo.GetList("GroupId=" + groupId).ToList();
            var objGroupPowerInfoComparer = new GroupPowerInfoComparer();
            List<GroupPowerInfo> objBatches = new List<GroupPowerInfo>();
            List<long> objPowerIds = new List<long>();
            foreach (var objGroupPowerInfo in objGroupPowerInfoListOld.Except(objGroupPowerInfoList, objGroupPowerInfoComparer))
            {
                objGroupPowerInfo.SetState(EntityStatus.Deleted);
                objBatches.Add(objGroupPowerInfo);
                objPowerIds.Add(objGroupPowerInfo.PowerId);
            }
            foreach (var objGroupPowerInfo in objGroupPowerInfoList.Except(objGroupPowerInfoListOld, objGroupPowerInfoComparer))
            {
                objGroupPowerInfo.SetState(EntityStatus.Added);
                objBatches.Add(objGroupPowerInfo);
            }
            //foreach (var objGroupPowerInfo in objGroupPowerInfoList.Intersect(objGroupPowerInfoListOld, objGroupPowerInfoComparer))
            //{
            //}
            int result = 0;
            if (objBatches.IsNoNull())
            {
                GroupPower objGroupPower = null;
                if (objPowerIds.IsNull())
                {
                    objBizGroupPowerInfo.ExecuteTransation(() =>
                    {
                        result = objBizGroupPowerInfo.Batch(objBatches, false);

                        if (IsCheckUserPowerRedis)
                        {
                            //更新Redis缓存
                            objGroupPower = new GroupPower
                            {
                                GroupId = groupId,
                                PowerIds = objBizGroupPowerInfo.GetFieldList<long>("GroupId=" + groupId, "PowerId")
                            };
                            RedisHelper.Store<GroupPower>(objGroupPower, PowerVariable.ProviderName, PowerVariable.Db);
                        }
                    }, true);
                }
                else
                {
                    objBizGroupPowerInfo.ExecuteTransation(() =>
                   {
                       this.DeleteUserPowers(objPowerIds, groupId);
                       result = objBizGroupPowerInfo.Batch(objBatches, false);

                       if (IsCheckUserPowerRedis)
                       {
                           //更新Redis缓存
                           objGroupPower = new GroupPower
                           {
                               GroupId = groupId,
                               PowerIds = objBizGroupPowerInfo.GetFieldList<long>("GroupId=" + groupId, "PowerId")
                           };
                           RedisHelper.Store<GroupPower>(objGroupPower, PowerVariable.ProviderName, PowerVariable.Db);
                       }
                   }, true);
                }
            }
            InvokeResult objInvokeResult = new InvokeResult();
            if (result < 0)
            {
                objInvokeResult.ResultCode = "Failed";
                objInvokeResult.ResultMessage = "保存失败";
            }
            else
            {
                objInvokeResult.ResultMessage = "保存成功";
            }
            return objInvokeResult;
        }
        /// <summary>
        /// 用户组继承权限-保存
        /// </summary>
        /// <param name="objUserPowerInfoList"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public InvokeResult SaveUserPower(List<UserPowerInfo> objUserPowerInfoList, long userId)
        {
            if (objUserPowerInfoList.IsNull())
            {
                objUserPowerInfoList = new List<UserPowerInfo>();
            }
            BizUserPowerInfo objBizUserPowerInfo = new BizUserPowerInfo();
            var objUserPowerInfoListOld = objBizUserPowerInfo.GetList("UserId=" + userId).ToList();
            var objUserPowerInfoComparer = new UserPowerInfoComparer();
            List<UserPowerInfo> objBatches = new List<UserPowerInfo>();
            foreach (var objUserPowerInfo in objUserPowerInfoListOld.Except(objUserPowerInfoList, objUserPowerInfoComparer))
            {
                objUserPowerInfo.SetState(EntityStatus.Deleted);
                objBatches.Add(objUserPowerInfo);
            }
            foreach (var objUserPowerInfo in objUserPowerInfoList.Except(objUserPowerInfoListOld, objUserPowerInfoComparer))
            {
                objUserPowerInfo.SetState(EntityStatus.Added);
                objBatches.Add(objUserPowerInfo);
            }
            //foreach (var objUserPowerInfo in objUserPowerInfoList.Intersect(objUserPowerInfoListOld, objUserPowerInfoComparer))
            //{
            //}
            int result = 0;
            if (objBatches.IsNoNull())
            {
                objBizUserPowerInfo.ExecuteTransation(() =>
                {
                    result = objBizUserPowerInfo.Batch(objBatches, false);

                    if (IsCheckUserPowerRedis)
                    {
                        UserPower objUserPower = new UserPower
                        {
                            UserId = userId,
                            PowerIds = objBizUserPowerInfo.GetFieldList<long>("UserId=" + userId, "PowerId")
                        };
                        RedisHelper.Store<UserPower>(objUserPower, PowerVariable.ProviderName, PowerVariable.Db);
                    }
                }, true);
            }
            InvokeResult objInvokeResult = new InvokeResult();
            if (result < 0)
            {
                objInvokeResult.ResultCode = "Failed";
                objInvokeResult.ResultMessage = "保存失败";
            }
            else
            {
                objInvokeResult.ResultMessage = "保存成功";
            }
            return objInvokeResult;
        }
        /// <summary>
        /// 用户独立权限-保存
        /// </summary>
        /// <param name="objUserPowerInfoList"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public InvokeResult SaveUserDependentPower(List<UserPowerInfo> objUserPowerInfoList, long userId)
        {
            if (objUserPowerInfoList.IsNull())
            {
                objUserPowerInfoList = new List<UserPowerInfo>();
            }
            BizUserPowerInfo objBizUserPowerInfo = new BizUserPowerInfo("Dependent");
            var objUserPowerInfoListOld = objBizUserPowerInfo.GetList("UserId=" + userId).ToList();
            var objUserPowerInfoComparer = new UserPowerInfoComparer();
            List<UserPowerInfo> objBatches = new List<UserPowerInfo>();
            foreach (var objUserPowerInfo in objUserPowerInfoListOld.Except(objUserPowerInfoList, objUserPowerInfoComparer))
            {
                objUserPowerInfo.SetState(EntityStatus.Deleted);
                objBatches.Add(objUserPowerInfo);
            }
            foreach (var objUserPowerInfo in objUserPowerInfoList.Except(objUserPowerInfoListOld, objUserPowerInfoComparer))
            {
                objUserPowerInfo.SetState(EntityStatus.Added);
                objBatches.Add(objUserPowerInfo);
            }
            //foreach (var objUserPowerInfo in objUserPowerInfoList.Intersect(objUserPowerInfoListOld, objUserPowerInfoComparer))
            //{
            //}
            int result = 0;
            if (objBatches.IsNoNull())
            {
                objBizUserPowerInfo.ExecuteTransation(() =>
                {
                    result = objBizUserPowerInfo.Batch(objBatches, false);

                    if (IsCheckUserPowerRedis)
                    {
                        UserPower objUserPower = new UserPower
                        {
                            UserId = userId,
                            PowerIds = objBizUserPowerInfo.GetFieldList<long>("UserId=" + userId, "PowerId")
                        };
                        RedisHelper.Store<UserPower>(objUserPower, PowerVariable.ProviderName, PowerVariable.Db, "Dependent");
                    }
                }, true);
            }
            InvokeResult objInvokeResult = new InvokeResult();
            if (result < 0)
            {
                objInvokeResult.ResultCode = "Failed";
                objInvokeResult.ResultMessage = "保存失败";
            }
            else
            {
                objInvokeResult.ResultMessage = "保存成功";
            }
            return objInvokeResult;
        }
        /// <summary>
        /// 角色用户-添加
        /// </summary>
        /// <param name="userIds"></param>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public InvokeResult SaveUserRoleInfo(List<long> userIds, long groupId)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (userIds.IsNull())
            {
                objInvokeResult.ResultCode = "ModelNull";
                objInvokeResult.ResultMessage = "保存失败";
                return objInvokeResult;
            }
            BizUserRoleInfo objBizUserRoleInfo = new BizUserRoleInfo();
            var objTargets = objBizUserRoleInfo.GetList("GroupId=" + groupId);
            List<UserRoleInfo> objBatches = new List<UserRoleInfo>();
            UserRoleInfo objUserRoleInfo = null;
            if (objTargets.IsNull())
            {
                foreach (var objUserId in userIds)
                {
                    objUserRoleInfo = new UserRoleInfo { GroupId = groupId, UserId = objUserId };
                    objUserRoleInfo.SetState(EntityStatus.Added);
                    objBatches.Add(objUserRoleInfo);
                }
            }
            else
            {
                int index = -1;
                foreach (var objUserId in userIds)
                {
                    index = objTargets.FindIndex(c => c.UserId == objUserId);
                    if (index >= 0)
                    {
                        continue;
                    }
                    objUserRoleInfo = new UserRoleInfo { GroupId = groupId, UserId = objUserId };
                    objUserRoleInfo.SetState(EntityStatus.Added);
                    objBatches.Add(objUserRoleInfo);
                }
            }
            int result = objBizUserRoleInfo.Batch(objBatches);

            if (IsCheckUserPowerRedis)
            {
                List<UserRole> objUserRoleList = new List<UserRole>();
                foreach (var objUserId in userIds)
                {
                    UserRole objUserRole = new UserRole
                    {
                        UserId = objUserId,
                        GroupIds = objBizUserRoleInfo.GetFieldList<long>("UserId=" + objUserId, "GroupId")
                    };
                    objUserRoleList.Add(objUserRole);
                }
                RedisHelper.StoreAll<UserRole>(objUserRoleList, PowerVariable.ProviderName, PowerVariable.Db);
            }
            else
            {
                string cachekey = string.Empty;
                foreach (long userId in userIds)
                {
                    cachekey = objBizUserRoleInfo.CreateCacheKey("UserId=" + userId, "GetViewDataTableCache", "*");
                    objBizUserRoleInfo.DeleteCache("", cachekey);

                }
            }

            if (result < 0)
            {
                objInvokeResult.ResultCode = "Failed";
                objInvokeResult.ResultMessage = "保存失败";
                return objInvokeResult;
            }
            objInvokeResult.ResultMessage = "保存成功";
            return objInvokeResult;
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public InvokeResult Login(string userName, string password)
        {
            InvokeResult objInvokeResult = new InvokeResult();
            if (userName.IsNull())
            {
                objInvokeResult.ResultCode = "UserNameNull";
                objInvokeResult.ResultMessage = "请输入用户名";
                return objInvokeResult;
            }
            if (password.IsNull())
            {
                objInvokeResult.ResultCode = "PasswordNull";
                objInvokeResult.ResultMessage = "请输入密码";
                return objInvokeResult;
            }
            BizUserInfo objBizUserInfo = new BizUserInfo();
            var objUserInfo = objBizUserInfo.GetRecord("UserName=@UserName AND Password=@Password", "UserName,Password".CreateSqlParameters(userName, password.EncodeMD5()));
            if (objUserInfo == null)
            {
                objInvokeResult.ResultCode = "LoginFailed";
                objInvokeResult.ResultMessage = "用户名或密码错误";
                return objInvokeResult;
            }
            objUserInfo.LoginDate = DateTime.Now;
            objUserInfo.LoginIP = RequestHelper.GetRealIp();
            objBizUserInfo.Update(objUserInfo);

            FormAuthHelper.SetUserTicket(objUserInfo.UserName, objUserInfo, DateTime.Now.AddHours(2), true);

            return objInvokeResult;
        }
        /// <summary>
        /// 用户登出
        /// </summary>
        public void LoginOut()
        {
            FormAuthHelper.ClearUserTicket();
        }
        /// <summary>
        /// 检查是否登录
        /// </summary>
        /// <returns></returns>
        public bool CheckLogin()
        {
            bool flag = FormAuthHelper.CheckUserTicket();
            if (flag)
            {
                return flag;
            }
            LoginOut();
            return flag;
        }
        /// <summary>
        /// 检查用户是否在线
        /// </summary>
        /// <returns></returns>
        public bool CheckOnLogin()
        {
            UserInfo objUserInfo = FormAuthHelper.GetUserTicket<UserInfo>();
            if (objUserInfo != null)
            {
                FormAuthHelper.SetUserTicket(objUserInfo.UserName, objUserInfo, DateTime.Now.AddHours(2), true);
                return true;
            }
            LoginOut();
            return false;
        }
    }

    public class GroupPowerInfoComparer : IEqualityComparer<GroupPowerInfo>
    {
        public bool Equals(GroupPowerInfo x, GroupPowerInfo y)
        {
            return x.PowerId == y.PowerId && x.GroupId == y.GroupId;
        }

        public int GetHashCode(GroupPowerInfo obj)
        {
            return obj.ToString().GetHashCode();
        }
    }
    public class UserPowerInfoComparer : IEqualityComparer<UserPowerInfo>
    {
        public bool Equals(UserPowerInfo x, UserPowerInfo y)
        {
            return x.PowerId == y.PowerId && x.UserId == y.UserId;
        }

        public int GetHashCode(UserPowerInfo obj)
        {
            return obj.ToString().GetHashCode();
        }
    }
    public class PowerInfoComparer : IEqualityComparer<PowerInfo>
    {
        public bool Equals(PowerInfo x, PowerInfo y)
        {
            return x.Id == y.Id;
        }

        public int GetHashCode(PowerInfo obj)
        {
            return obj.ToString().GetHashCode();
        }
    }
}
